<template>
  <div class="personal-container">
    <el-tabs v-model="activeTab" class="personal-tabs">
      <el-tab-pane label="个人信息" name="info">
        <el-card class="personal-card">
          <div class="personal-header">
            <div class="avatar-section">
              <el-avatar :src="userInfo.avatar" :size="100" />
              <el-button type="primary" @click="handleAvatarUpload" class="upload-btn">
                更换头像
              </el-button>
            </div>
            <div class="info-section">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="用户名">{{ userInfo.username }}</el-descriptions-item>
                <el-descriptions-item label="姓名">{{ userInfo.name }}</el-descriptions-item>
                <el-descriptions-item label="手机号">{{ userInfo.mobile }}</el-descriptions-item>
                <el-descriptions-item label="性别">
                  {{ userInfo.sex === 1 ? '男' : '女' }}
                </el-descriptions-item>
                <el-descriptions-item label="所在部门">
                  {{ userInfo.department }}
                </el-descriptions-item>
                <el-descriptions-item label="岗位职称">
                  {{ userInfo.position }}
                </el-descriptions-item>
                <el-descriptions-item label="员工类型">
                  <el-tag v-if="userInfo.type === 1">正式员工</el-tag>
                  <el-tag v-else-if="userInfo.type === 2" type="warning">试用员工</el-tag>
                  <el-tag v-else-if="userInfo.type === 3" type="success">实习生</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="入职日期">
                  {{ userInfo.entry_time }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </div>

          <div class="personal-form">
            <el-form :model="personalForm" label-width="100px" ref="personalFormRef">
              <el-form-item label="个人简介">
                <el-input
                  v-model="personalForm.desc"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入个人简介"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="savePersonalInfo">保存信息</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="修改密码" name="password">
        <el-card class="password-card">
          <el-form
            :model="passwordForm"
            :rules="passwordRules"
            label-width="120px"
            ref="passwordFormRef"
            class="password-form"
          >
            <el-form-item label="旧密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                placeholder="请输入旧密码"
                show-password
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                show-password
              />
            </el-form-item>
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                placeholder="请再次输入新密码"
                show-password
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="changePassword">修改密码</el-button>
              <el-button @click="resetPasswordForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 头像上传对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="上传头像" width="500px">
      <el-upload
        class="avatar-uploader"
        drag
        :action="uploadUrl"
        :headers="uploadHeaders"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { useUserStore } from '@/store/user'
  import { useHomeStore } from '@/store/home'
  import { ElMessage } from 'element-plus'

  const userStore = useUserStore()
  const homeStore = useHomeStore()

  const activeTab = ref('info')
  const uploadDialogVisible = ref(false)

  // 用户信息
  const userInfo = ref({
    id: 0,
    username: '',
    name: '',
    avatar: '',
    mobile: '',
    sex: 1,
    department: '',
    position: '',
    type: 1,
    entry_time: '',
  })

  // 个人信息表单
  const personalForm = reactive({
    desc: '',
  })

  // 密码表单
  const passwordForm = reactive({
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
  })

  // 密码验证规则
  const passwordRules = {
    oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
    newPassword: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
    ],
    confirmPassword: [
      { required: true, message: '请再次输入新密码', trigger: 'blur' },
      {
        validator: (_rule: any, value: string, callback: any) => {
          if (value !== passwordForm.newPassword) {
            callback(new Error('两次输入的密码不一致'))
          } else {
            callback()
          }
        },
        trigger: 'blur',
      },
    ],
  }

  // 上传相关
  const uploadUrl = '/index/upload'
  const uploadHeaders = {
    Authorization: `Bearer ${localStorage.getItem('token')}`,
  }

  // 获取用户信息
  const loadUserInfo = async () => {
    try {
      // 直接从userStore获取用户信息，避免重复请求接口
      if (userStore.userInfo && userStore.userInfo.id) {
        userInfo.value = {
          ...userInfo.value,
          ...userStore.userInfo,
        }
      }
      // 如果用户信息不存在，由路由守卫处理，这里不主动请求
    } catch (error) {
      ElMessage.error('获取用户信息失败')
    }
  }

  // 保存个人信息
  const personalFormRef = ref()
  const savePersonalInfo = async () => {
    try {
      const formData = new FormData()
      formData.append('desc', personalForm.desc)
      const res: any = await homeStore.editPersonalAction(formData)

      if (res && res.code === 0) {
        ElMessage.success('保存成功')
      } else {
        ElMessage.error((res && res.msg) || '保存失败')
      }
    } catch (error) {
      ElMessage.error('保存失败')
    }
  }

  // 修改密码
  const passwordFormRef = ref()
  const changePassword = async () => {
    if (!passwordFormRef.value) return

    await passwordFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          const formData = new FormData()
          formData.append('old_pwd', passwordForm.oldPassword)
          formData.append('pwd', passwordForm.newPassword)
          formData.append('pwd_confirm', passwordForm.confirmPassword)
          const res: any = await homeStore.editPasswordAction(formData)

          if (res && res.code === 0) {
            ElMessage.success('密码修改成功，请重新登录')
            // 清除本地存储的token
            localStorage.removeItem('token')
            // 跳转到登录页
            window.location.href = '/login'
          } else {
            ElMessage.error((res && res.msg) || '密码修改失败')
          }
        } catch (error) {
          ElMessage.error('密码修改失败')
        }
      }
    })
  }

  // 重置密码表单
  const resetPasswordForm = () => {
    passwordForm.oldPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
    if (passwordFormRef.value) {
      passwordFormRef.value.resetFields()
    }
  }

  // 处理头像上传
  const handleAvatarUpload = () => {
    uploadDialogVisible.value = true
  }

  // 头像上传成功处理
  const handleAvatarSuccess = (response: any) => {
    if (response.code === 0) {
      ElMessage.success('头像上传成功')
      userInfo.value.avatar = response.data.filepath
      uploadDialogVisible.value = false
    } else {
      ElMessage.error(response.msg || '上传失败')
    }
  }

  // 头像上传前检查
  const beforeAvatarUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isJPG) {
      ElMessage.error('头像图片只能是 JPG 或 PNG 格式!')
    }
    if (!isLt2M) {
      ElMessage.error('头像图片大小不能超过 2MB!')
    }

    return isJPG && isLt2M
  }

  // 初始化加载
  onMounted(() => {
    loadUserInfo()
  })
</script>

<style scoped>
  .personal-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: calc(100vh - 100px);
  }

  .personal-tabs {
    background: white;
    padding: 20px;
    border-radius: 4px;
  }

  .personal-header {
    display: flex;
    margin-bottom: 30px;
    padding-bottom: 30px;
    border-bottom: 1px solid #eee;
  }

  .avatar-section {
    width: 200px;
    text-align: center;
    margin-right: 40px;
  }

  .upload-btn {
    margin-top: 15px;
  }

  .info-section {
    flex: 1;
  }

  .personal-form {
    margin-top: 30px;
  }

  .password-card {
    max-width: 600px;
  }

  .password-form {
    margin-top: 20px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
</style>
